<template>
  <el-card class="clubListMain" style="max-width: 75vw">
    <div>
      <el-input class="searchText" v-model="clubNameSearch" placeholder="输入社团名" />
      <el-button type="primary" @click="handleResearch">查询</el-button>
    </div>
    <div>
      <el-table class="listTable" :data="clubListData" :border=true style="width: 100%" :max-height="'70vh'">
        <el-table-column prop="clubName" label="社团名称" :width="tableWidth[0]" :align="'center'" />
        <el-table-column prop="level" label="社团级别" :width="tableWidth[1]" :align="'center'" />
        <el-table-column prop="number" label="社团人数" :width="tableWidth[2]" :align="'center'" />
        <el-table-column prop="status" label="社团状态" :width="tableWidth[3]" :align="'center'" />
        <el-table-column prop="options" label="操作" :width="tableWidth[4]" :align="'center'">
          <template #default="scope">
            <el-button id="buttonClubShow" @click="handleShowClub(scope.row)">查看社团详情</el-button>
            <el-button id="buttonClubAdd" :disabled="scope.row.disabled"
              @click="handleJoinButton(scope.row)">申请加入</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="footerpager">
      <el-select v-model="pageSize" @change="onOptionChange" placeholder="Select" style="width: 120px">
        <el-option v-for="size in pageSizeOptions" :key="size.value" :label="size.label" :value="size.value" />
      </el-select>
      <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
        :pager-count="7" @current-change="handleUpdateList" layout="prev, pager, next" :total="totalNum" />
      <div class="pageNow">
        当前
        <input class="pageInput" @blur="onChangePage" v-model="setCurrentPage" />
        页，共
        {{ totalPage }}
        页
      </div>
    </div>
  </el-card>
  <el-dialog v-model="joinDialogVisible" :title="joinTitle" width="500">
    <el-form-item label="申请原因">
      <el-input v-model="reason" type="textarea" maxlength="200" show-word-limit placeholder="请输入申请原因" />
    </el-form-item>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="joinDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleJoinClub">申请</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { onMounted, reactive, ref, watch,onUnmounted } from 'vue';
import api from '@/api';
import showMessageTip from '@/utils/showMessage';
import router from '@/router';
import userStore from '@/stores/store';
import debounce from '@/utils/debounce';

const clubNameSearch = ref('');
const clubListData = ref([]);
const tableWidth=ref([]);
const pageSize = ref(10);
const tableWidthRatio=ref([0.25,0.13,0.1,0.17,0.35]);
const totalPage = ref(1); //总页数
const pageSizeOptions = ref([
  { value: 5, label: '5条/页' },
  { value: 10, label: '10条/页' },
  { value: 15, label: '15条/页' },
  { value: 20, label: '20条/页' },
]);
const totalNum = ref(0);
const currentPage = ref(1);
const setCurrentPage = ref();
const joinDialogVisible = ref(false);
const joinTitle = ref('申请加入社团');
const reason = ref('');
const selectedClub = ref(null);
var debounceSetColumnSize = null;

onMounted(async  () => {
  const width = document.querySelector('.clubListMain').getBoundingClientRect().width-40;
  tableWidth.value[4]=width;
  for(let i = 0; i<4 ;i++){
    tableWidth.value[i] = tableWidthRatio.value[i]*width;
    tableWidth.value[4] -= tableWidth.value[i];
  }
  handleUpdateList();
});
onMounted( () => {
  debounceSetColumnSize = debounce(setColumnSize, 300);
  window.addEventListener('resize', debounceSetColumnSize);
})
onUnmounted(() => {
  window.removeEventListener('resize', debounceSetColumnSize);
  debounceSetColumnSize.cancel();
});
const setColumnSize = () => {
  const width = document.querySelector('.clubListMain').getBoundingClientRect().width-40;
  tableWidth.value[4]=width;
  for(let i = 0; i<4 ;i++){
    tableWidth.value[i] = tableWidthRatio.value[i]*width;
    tableWidth.value[4] -= tableWidth.value[i];
  }
}
const handleUpdateList = async () => {
  const reqData = reactive({
    page:currentPage.value,
    pageSize:pageSize.value,
  })
  if(clubNameSearch.value != ''){
    reqData.clubName = clubNameSearch.value;
  }
  const resultList =await api.getClubList(reqData);
  switch(resultList[0])
    {
      case 0:
        const data = resultList[1].data;
        if(data.code == 1){
          totalNum.value = data.data.total;
          const tableData = data.data.rows;
          clubListData.value = [];
          for(let i=0;i<tableData.length;i++){
            const temp = reactive({});
            if(tableData[i].clubLevel == 0){
              temp.level = "校级";
            }
            else{
              temp.level = "院级";
            }
            if(tableData[i].clubState == 0){
              temp.disabled = false;

              temp.status = "可加入"
            }
            else if(tableData[i].clubState == 1){
              temp.disabled = true;
              temp.status = "不可加入";
            }
            else{
              temp.disabled = true;
              temp.status = "停用";
            }
            Object.assign(temp,{
              clubName:tableData[i].clubName,
              number:tableData[i].number,
              clubId:tableData[i].clubId,
            });
            clubListData.value[i] = temp;
          }
          totalPage.value = Math.ceil(data.data.total/pageSize.value);
        }
        else{
          showMessageTip("加载失败！",'error');
          return;
        }
        break;
      case 1:
        showMessageTip("服务器响应错误，代码:"+resultList[1].status+"，请再次尝试",'error')
        break;
      case 2:
        showMessageTip("连接服务器失败,请检查网络",'error')
        break;
      case 3:
        showMessageTip("请求发送失败",'error')
        break;
    }
  setCurrentPage.value = currentPage.value;
}
const handleJoinButton = async (rowData) =>{
  selectedClub.value = rowData.clubId;
  joinTitle.value = "申请加入"+rowData.clubName;
  joinDialogVisible.value = true;
}

const handleResearch= async ()=>{
  setCurrentPage.value = 1;
  currentPage.value = 1;
  await handleUpdateList();
}
const onChangePage = () => {
  if(Number(setCurrentPage.value) > totalPage.value){
    setCurrentPage.value = totalPage.value;
    currentPage.value = totalPage.value;
  }
  else if(setCurrentPage.value <= 0){
    setCurrentPage.value = 1;
    currentPage.value = 1;
  }
  else{
    currentPage.value = Number(setCurrentPage.value);
  }
  handleUpdateList();
}
const onOptionChange = () => {
  setCurrentPage.value = 1;
  currentPage.value = 1;
}
watch(pageSize, async (newQuestion, oldQuestion) =>{
  await handleUpdateList();
})

const handleJoinClub = async () => {
  const reqData = reactive({
    bigAffairType: 2,
    affairType: 1,
    clubId:selectedClub.value,
    reason:reason.value,
  })
  const result = await api.joinClub(reqData);
  if(result[0] == 0){
    const data = result[1].data;
    if(data.code == 1){
      showMessageTip("申请成功",'success');
      joinDialogVisible.value = false;
      reason.value = '';
    }
    else if(data.msg == "already exist"){
      showMessageTip("已加入该社团，无法重复申请",'warning');
      joinDialogVisible.value = false;
    }
    else{
      showMessageTip("申请失败",'error');
      return;
    }
  }
  else{
    showMessageTip("申请失败",'error');
    return;
  }
}

const handleShowClub = (rowData) => {
  userStore().setClubID(rowData.clubId);
  router.push('/managesys/clubview');
}
</script>

<style scoped>
.pagdivisiong {
  left: 40%;
  position: relative;
}
.searchText{
  width: 240px;
  margin-right: 20px;
}
.tableClass{
  text-align: center;
}
.listTable{
  margin-top: 12px;
}
:deep(.listTable .el-table__header-wrapper th){
  background-color: #549DFD;
  color: #fff;
  font-family: 'Microsoft YaHei';
}
#buttonClubAdd{
  border: none;
  background-color:#2cad2c;
  color: #fff;
}
#buttonClubAdd:disabled{
  background-color: #dbdada;
}
#buttonClubAdd:hover:not(:disabled){
  background-color: #008200;
}

#buttonClubShow{
  border:#549DFD 1.5px solid ;
  color: #549DFD;
}
.footerpager{
  margin-top: 20px;
  padding-left: 5px;
  display: flex;
}
.pageNow{
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14.5px;
}
.pageInput{
  margin-left: 5px;
  margin-right: 5px;
  width: 25px;
  text-align: center;
}
</style>